package web;

import pojo.Cart;
import pojo.Order;
import pojo.User;
import service.OrderService;
import service.impl.OrderSrtviceLmpl;
import utils.JDBCutils;
import utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class OrderServlet extends BaseServlet {
    private OrderService o = new OrderSrtviceLmpl();

    //创建订单号
    protected void createOrderNumber(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        String id = req.getParameter("id");
        if (cart != null) {
            String order = o.createOrder(cart, WebUtils.paraseInt(id, 0));
            req.getSession().setAttribute("orderNumber", order);
            System.out.println(order);
            resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");
        } else {
            resp.sendRedirect(req.getContextPath() + "/pages/cart/cart.jsp");
        }
    }

    //展示所有订单信息
    protected void showAllOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        System.out.println(user);
        List<Order> orders = o.showMyOrders(user.getId());
        System.out.println(orders);
        req.getSession().setAttribute("orders", orders);
        resp.sendRedirect(req.getContextPath() + "/pages/order/order.jsp");
    }

    //管理员大哥的查看订单
    protected void showAllOrderss(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Order> orders = o.showAllOrders();
            JDBCutils.rollBack();
        System.out.println(orders);
        req.getSession().setAttribute("order", orders);
        resp.sendRedirect(req.getContextPath() + "/pages/manager/order_manager.jsp");
    }

    protected void sendGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("OrderId");
        if(orderId!=null){
            try {
                o.sendOrder(orderId);
                JDBCutils.closeAndCommit();
            } catch (Exception e) {
                JDBCutils.rollBack();
                e.printStackTrace();
            }
            resp.sendRedirect(req.getContextPath()+"/client/OrderServlet?action=showAllOrderss");
        }else {
            resp.sendRedirect(req.getContextPath()+"/pages/manager/order_manager.jsp");
        }
    }
}